package com.talkweb.citypickerview.style.citypickerview;

import com.talkweb.citypickerview.Interface.OnCityItemClickListener;
import com.talkweb.citypickerview.ResourceTable;
import com.talkweb.citypickerview.bean.CityBean;
import com.talkweb.citypickerview.bean.DistrictBean;
import com.talkweb.citypickerview.bean.ProvinceBean;
import com.talkweb.citypickerview.citywheel.CityConfig;
import com.talkweb.citypickerview.citywheel.CityParseHelper;
import com.talkweb.citypickerview.style.citylist.Toast.ToastUtils;
import com.talkweb.citypickerview.style.citypickerview.widget.CanShow;
import com.talkweb.citypickerview.style.citypickerview.widget.wheel.WheelPicker;
import com.talkweb.citypickerview.utils.TextUtils;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.app.Context;

import java.util.ArrayList;
import java.util.List;

/**
 * 省市区三级选择
 * 作者：liji on 2015/12/17 10:40
 * 邮箱：lijiwork@sina.com
 */
public class CityPickerView implements CanShow, Picker.ValueChangedListener {

    private CommonDialog popwindow;

    private Component popview;

    private WheelPicker mViewProvince;

    private WheelPicker mViewCity;

    private WheelPicker mViewDistrict;

    private DependentLayout mRelativeTitleBg;

    private Text mTvOK;

    private Text mTvTitle;

    private Text mTvCancel;

    private OnCityItemClickListener mBaseListener;

    private CityParseHelper parseHelper;

    private CityConfig config;

    private Context context;

    private List<ProvinceBean> proArra;

    public void setOnCityItemClickListener(OnCityItemClickListener listener) {
        mBaseListener = listener;
    }

    /**
     * 设置属性
     *
     * @param config
     */
    public void setConfig(final CityConfig config) {
        this.config = config;
    }

    /**
     * 初始化，默认解析城市数据，提交加载速度
     */
    public void init(Context context) {
        this.context = context;
        parseHelper = new CityParseHelper();

        //解析初始数据
        if (parseHelper.getProvinceBeanArrayList().isEmpty()) {
            parseHelper.initData(context);
        }

    }

    /**
     * 初始化popWindow
     */
    private void initCityPickerPopwindow() {
        if (config == null) {
            throw new IllegalArgumentException("please set config first...");
        }

        //解析初始数据
        if (parseHelper == null) {
            parseHelper = new CityParseHelper();
        }

        if (parseHelper.getProvinceBeanArrayList().isEmpty()) {
            ToastUtils.showLongToast(context, "请在Activity中增加init操作");
            return;
        }

        LayoutScatter layoutInflater = LayoutScatter.getInstance(context);
        popview = layoutInflater.parse(ResourceTable.Layout_pop_citypicker, null, false);

        mViewProvince = (WheelPicker) popview.findComponentById(ResourceTable.Id_id_province);
        mViewCity = (WheelPicker) popview.findComponentById(ResourceTable.Id_id_city);
        mViewDistrict = (WheelPicker) popview.findComponentById(ResourceTable.Id_id_district);
        mRelativeTitleBg = (DependentLayout) popview.findComponentById(ResourceTable.Id_rl_title);
        mTvOK = (Text) popview.findComponentById(ResourceTable.Id_tv_confirm);
        mTvTitle = (Text) popview.findComponentById(ResourceTable.Id_tv_title);
        mTvCancel = (Text) popview.findComponentById(ResourceTable.Id_tv_cancel);

        popwindow = new CommonDialog(context);
        popwindow.setContentCustomComponent(popview);
        popwindow.setAlignment(LayoutAlignment.CENTER);
        popwindow.setAutoClosable(true);

        /**
         * 设置标题背景颜色
         */
        if (!TextUtils.isEmpty(config.getTitleBackgroundColorStr())) {
            if (config.getTitleBackgroundColorStr().startsWith("#")) {
                ShapeElement element = new ShapeElement();
                element.setRgbColor(new RgbColor());
                element.setRgbColor(new RgbColor(Color.getIntColor(config.getTitleBackgroundColorStr())));
                mRelativeTitleBg.setBackground(element);
            } else {
                ShapeElement element = new ShapeElement();
                element.setRgbColor(new RgbColor());
                element.setRgbColor(new RgbColor(Color.getIntColor("#" + config.getTitleBackgroundColorStr())));
                mRelativeTitleBg.setBackground(element);
            }
        }

        //标题
        if (!TextUtils.isEmpty(config.getTitle())) {
            mTvTitle.setText(config.getTitle());
        }

        //标题文字大小
        if (config.getTitleTextSize() > 0) {
            mTvTitle.setTextSize(config.getTitleTextSize(), Text.TextSizeType.FP);
        }
        //标题文字颜色
        if (!TextUtils.isEmpty(config.getTitleTextColorStr())) {
            if (config.getTitleTextColorStr().startsWith("#")) {
                mTvTitle.setTextColor(new Color(Color.getIntColor(config.getTitleTextColorStr())));
            } else {
                mTvTitle.setTextColor(new Color(Color.getIntColor("#" + config.getTitleTextColorStr())));
            }
        }

        //设置确认按钮文字大小颜色
        if (!TextUtils.isEmpty(config.getConfirmTextColorStr())) {
            if (config.getConfirmTextColorStr().startsWith("#")) {
                mTvOK.setTextColor(new Color(Color.getIntColor(config.getConfirmTextColorStr())));
            } else {
                mTvOK.setTextColor(new Color(Color.getIntColor("#" + config.getConfirmTextColorStr())));
            }
        }

        if (!TextUtils.isEmpty(config.getConfirmText())) {
            mTvOK.setText(config.getConfirmText());
        }

        if ((config.getConfirmTextSize() > 0)) {
            mTvOK.setTextSize(config.getConfirmTextSize(), Text.TextSizeType.FP);
        }

        //设置取消按钮文字颜色
        if (!TextUtils.isEmpty(config.getCancelTextColorStr())) {
            if (config.getCancelTextColorStr().startsWith("#")) {
                mTvCancel.setTextColor(new Color(Color.getIntColor(config.getCancelTextColorStr())));
            } else {
                mTvCancel.setTextColor(new Color(Color.getIntColor("#" + config.getCancelTextColorStr())));
            }
        }

        if (!TextUtils.isEmpty(config.getCancelText())) {
            mTvCancel.setText(config.getCancelText());
        }

        if ((config.getCancelTextSize() > 0)) {
            mTvCancel.setTextSize(config.getCancelTextSize(), Text.TextSizeType.FP);
        }

        //只显示省市两级联动
        if (config.getWheelType() == CityConfig.WheelType.PRO) {
            mViewCity.setVisibility(Component.HIDE);
            mViewDistrict.setVisibility(Component.HIDE);
        } else if (config.getWheelType() == CityConfig.WheelType.PRO_CITY) {
            mViewDistrict.setVisibility(Component.HIDE);
        } else {
            mViewProvince.setVisibility(Component.VISIBLE);
            mViewCity.setVisibility(Component.VISIBLE);
            mViewDistrict.setVisibility(Component.VISIBLE);
        }

        // 添加change事件
        mViewProvince.setValueChangedListener(this);
        // 添加change事件
        mViewCity.setValueChangedListener(this);
        // 添加change事件
        mViewDistrict.setValueChangedListener(this);
        // 添加onclick事件
        mTvCancel.setClickedListener(v -> {
            mBaseListener.onCancel();
            hide();
        });

        //确认选择
        mTvOK.setClickedListener(v -> {
            if (parseHelper != null) {
                if (config.getWheelType() == CityConfig.WheelType.PRO) {
                    mBaseListener.onSelected(parseHelper.getProvinceBean(), new CityBean(), new DistrictBean());
                } else if (config.getWheelType() == CityConfig.WheelType.PRO_CITY) {
                    mBaseListener.onSelected(parseHelper.getProvinceBean(),
                            parseHelper.getCityBean(),
                            new DistrictBean());
                } else {
                    mBaseListener.onSelected(parseHelper.getProvinceBean(),
                            parseHelper.getCityBean(),
                            parseHelper.getDistrictBean());
                }

            } else {
                mBaseListener.onSelected(new ProvinceBean(), new CityBean(), new DistrictBean());
            }
            hide();
        });

        //显示省市区数据
        setUpData();

        //背景半透明
        if (config != null && config.isShowBackground()) {
            popwindow.setTransparent(true);
        }

    }

    /**
     * 根据是否显示港澳台数据来初始化最新的数据
     *
     * @param array
     * @return
     */
    private List<ProvinceBean> getProArrData(List<ProvinceBean> array) {

        List<ProvinceBean> provinceBeanList = new ArrayList<>();
        for (int i = 0; i < array.size(); i++) {
            provinceBeanList.add(array.get(i));
        }

        //不需要港澳台数据
        if (!config.isShowGAT()) {
            provinceBeanList.remove(provinceBeanList.size() - 1);
            provinceBeanList.remove(provinceBeanList.size() - 1);
            provinceBeanList.remove(provinceBeanList.size() - 1);
        }

        proArra = new ArrayList<ProvinceBean>();
        for (int i = 0; i < provinceBeanList.size(); i++) {
            proArra.add(provinceBeanList.get(i));
        }

        return proArra;
    }

    /**
     * 加载数据
     */
    private void setUpData() {
        if (parseHelper == null || config == null) {
            return;
        }

        //根据是否显示港澳台数据来初始化最新的数据
        getProArrData(parseHelper.getProvinceBeenArray());

        int provinceDefault = 0;
        if (!TextUtils.isEmpty(config.getDefaultProvinceName()) && proArra.size() > 0) {
            for (int i = 0; i < proArra.size(); i++) {
                if (proArra.get(i).getName().equals(config.getDefaultProvinceName())) {
                    provinceDefault = i;
                    break;
                }
            }
        }

        //获取所设置的省的位置，直接定位到该位置
        mViewProvince.setDisplayedData(proArra);
        mViewProvince.setMaxValue(proArra.size());
        mViewProvince.setValue(provinceDefault);

        mViewProvince.setFormatter(i -> proArra.get(i).getName());
        // 设置可见条目数量
        mViewProvince.setSelectorItemNum(config.getVisibleItems());
        mViewCity.setSelectorItemNum(config.getVisibleItems());
        mViewDistrict.setSelectorItemNum(config.getVisibleItems());
        mViewProvince.setWheelModeEnabled(config.isProvinceCyclic());
        mViewCity.setWheelModeEnabled(config.isCityCyclic());
        mViewDistrict.setWheelModeEnabled(config.isDistrictCyclic());

        //中间线的颜色及高度
        ShapeElement shape = new ShapeElement();
        shape.setShape(ShapeElement.RECTANGLE);
        shape.setStroke(config.getLineHeigh(),
                new RgbColor(AttrHelper.convertValueToColor(config.getLineColor()).getValue()));

        mViewProvince.setDisplayedLinesElements(shape, shape);
        mViewCity.setDisplayedLinesElements(shape, shape);
        mViewDistrict.setDisplayedLinesElements(shape, shape);

        if (config.getWheelType() != CityConfig.WheelType.PRO) {
            updateCities();
        }
    }

    /**
     * 根据当前的省，更新市WheelView的信息
     */
    private void updateCities() {
        if (parseHelper == null || config == null) {
            return;
        }

        //省份滚轮滑动的当前位置
        int pCurrent = mViewProvince.getValue() % proArra.size();

        //省份选中的名称
        ProvinceBean mProvinceBean = proArra.get(pCurrent);
        parseHelper.setProvinceBean(mProvinceBean);

        if (parseHelper.getPro_CityMap() == null) {
            return;
        }

        List<CityBean> cities = parseHelper.getPro_CityMap().get(mProvinceBean.getName());
        if (cities == null) {
            return;
        }

        //设置最初的默认城市
        int cityDefault = -1;
        if (!TextUtils.isEmpty(config.getDefaultCityName()) && cities.size() > 0) {
            for (int i = 0; i < cities.size(); i++) {
                if (config.getDefaultCityName().equals(cities.get(i).getName())) {
                    cityDefault = i;
                    break;
                }
            }
        }

        if (-1 != cityDefault) {
            mViewCity.setValue(cityDefault);
        } else {
            mViewCity.setValue(0);
        }
        mViewCity.setDisplayedData(cities);
        mViewCity.setMaxValue(cities.size());
        parseHelper.setCityBean(cities.get(mViewCity.getValue()));

        if (config.getWheelType() == CityConfig.WheelType.PRO_CITY_DIS) {
            updateAreas();
        }
    }

    /**
     * 根据当前的市，更新区WheelView的信息
     */
    private void updateAreas() {
        int pCurrent = mViewCity.getValue();
        if (parseHelper.getPro_CityMap() == null || parseHelper.getCity_DisMap() == null) {
            return;
        }

        if (config.getWheelType() == CityConfig.WheelType.PRO_CITY
                || config.getWheelType() == CityConfig.WheelType.PRO_CITY_DIS) {
            List<CityBean> cityBeanList = parseHelper.getPro_CityMap().get(parseHelper.getProvinceBean().getName());
            if (pCurrent >= cityBeanList.size()) {
                return;
            }
            CityBean mCityBean = cityBeanList.get(pCurrent % cityBeanList.size());
            parseHelper.setCityBean(mCityBean);

            if (config.getWheelType() == CityConfig.WheelType.PRO_CITY_DIS) {
                List<DistrictBean> areas = parseHelper.getCity_DisMap()
                        .get(parseHelper.getProvinceBean().getName() + mCityBean.getName());
                if (areas == null) {
                    return;
                }

                int districtDefault = -1;
                if (!TextUtils.isEmpty(config.getDefaultDistrict()) && areas.size() > 0) {
                    for (int i = 0; i < areas.size(); i++) {
                        if (config.getDefaultDistrict().equals(areas.get(i).getName())) {
                            districtDefault = i;
                            break;
                        }
                    }
                }

                DistrictBean mDistrictBean = null;
                if (parseHelper.getDisMap() == null) {
                    return;
                }

                if (-1 != districtDefault) {
                    mViewDistrict.setValue(districtDefault);
                    //获取第一个区名称
                    mDistrictBean = parseHelper.getDisMap().get(parseHelper.getProvinceBean().getName()
                            + mCityBean.getName() + config.getDefaultDistrict());
                } else {
                    mViewDistrict.setValue(0);
                    if (areas.size() > 0) {
                        mDistrictBean = areas.get(0);
                    }
                }

                mViewDistrict.setDisplayedData(areas);
                mViewDistrict.setMaxValue(areas.size());
                parseHelper.setDistrictBean(mDistrictBean);
            }
        }
    }

    public void showCityPicker() {
        initCityPickerPopwindow();
        if (!isShow()) {
            popwindow.show();
        }
    }

    @Override
    public void hide() {
        if (isShow()) {
            popwindow.hide();
        }
    }

    @Override
    public boolean isShow() {
        return popwindow.isShowing();
    }

    @Override
    public void onValueChanged(Picker wheel, int oldValue, int newValue) {
        System.out.println("old:" + oldValue + "," + newValue + "," + mViewDistrict.getMaxValue());
        if (wheel == mViewProvince) {
            updateCities();
        } else if (wheel == mViewCity) {
            updateAreas();
        } else if (wheel == mViewDistrict && parseHelper != null && parseHelper.getCity_DisMap() != null) {
            List<DistrictBean> mDistrictBeanList = parseHelper.getCity_DisMap()
                    .get(parseHelper.getProvinceBean().getName()
                            + parseHelper.getCityBean().getName());

            if (mDistrictBeanList == null || mDistrictBeanList.size() <= newValue) {
                return;
            }

            parseHelper.setDistrictBean(mDistrictBeanList.get(newValue % mDistrictBeanList.size()));
        }
    }

}
